package com.erp.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.order.api.domain.ErpSellerChildOrder;
import com.ruoyi.order.api.domain.ErpSellerOrder;
import com.ruoyi.order.api.domain.ErpSellerOrderProduct;
import com.ruoyi.order.api.domain.ErpSellerOrderExtend;
import com.ruoyi.order.api.domain.ErpSellerOrderLog;
import com.ruoyi.common.core.enums.OrderLogType;
import com.ruoyi.common.core.enums.OrderProcessFlag;
import com.erp.order.mapper.*;
import com.erp.order.service.IAeSaveOrderService;
import com.erp.order.service.IErpSellerOrderLogService;
import com.ruoyi.ae.api.RemoteAeOrderService;
import com.ruoyi.ae.api.domain.PullOrderFromAeParam;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.TimeZoneTransition;
import com.ruoyi.gather.api.RemoteCollectAbsentSkuService;
import com.ruoyi.gather.api.RemoteCollectProductService;
import com.ruoyi.gather.api.RemoteCollectProductSkuService;
import com.ruoyi.gather.api.domain.ErpCollectAbsentSku;
import com.ruoyi.gather.api.domain.ErpCollectProductSku;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
//import com.erp.order.api.domain.ErpSellerChildOrder;
//import com.erp.order.api.domain.ErpSellerOrder;
//import com.erp.order.api.domain.ErpSellerOrderProduct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class AeSaveOrderServiceImpl implements IAeSaveOrderService {

    @Resource
    private RemoteAeOrderService remoteAeOrderService;
    @Resource
    private RemoteCollectProductService remoteCollectProductService;
    @Resource
    private RemoteCollectProductSkuService remoteCollectProductSkuService;
    @Resource
    private RemoteCollectAbsentSkuService remoteCollectAbsentSkuService;
    @Resource
    private RemoteSellerStoreService remoteSellerStoreService;

//    @Autowired
//    RestTemplate restTemplate;
//    @Autowired
//    ISysConfigService configService;
//    @Autowired
//    IErpSellerStoreEmpowerService iErpSellerStoreEmpowerService;
//    @Autowired
//    IErpSellerOrderService iErpSellerOrderService;
    private final ErpSellerOrderMapper erpSellerOrderMapper;
//    private final ErpCollectProductSkuMapper erpCollectProductSkuMapper;
//    private final IErpSellerOrderLogService orderLogService;
//    private final IErpSellerStoreEmpowerService erpSellerStoreEmpowerService;
//    private final ErpCollectAbsentSkuMapper erpCollectAbsentSkuMapper;
    private final ErpSellerOrderProductMapper erpSellerOrderProductMapper;
    private final ErpSellerOrderExtendMapper erpSellerOrderExtendMapper;
//    private final IErpOrderProductStatisticsService iErpOrderProductStatisticsService;
//    private final IErpOrderInfoStatisticsService orderInfoStatisticsService;
    private final ErpSellerChildOrderMapper erpSellerChildOrderMapper;
//    private final ErpSellerStoreEmpowerMapper erpSellerStoreEmpowerMapper;
//
//    private final AEConfig aeConfig;
//    private final ErpSellerStoreProductEvaluationMapper erpSellerStoreProductEvaluationMapper;
//    private final ErpSellerStoreEmpowerMapper empowerMapper;
    private final IErpSellerOrderLogService erpSellerOrderLogService;
    private final ErpSellerOrderLogMapper erpSellerOrderLogMapper;
//    private final IErpInternetCelebrityStatisticService iErpInternetCelebrityStatisticService;
//    private final IErpCollectProductService iErpCollectProductService;
//
//    //订单状态策略
    private static Map<String, Object> orderStatusTacticsMap = OrderProcessFlag.getOrderStatusCollocationMap();
    String statusStr = "WAIT_BUYER_ACCEPT_GOODS,PLACE_ORDER_SUCCESS,WAIT_SELLER_SEND_GOODS,FINISH,RISK_CONTROL";
    //    String errorFinishStatus = "begin,cainiao,offline,cutoff,cutoff";
    String inProcessOrderStatus = "103,1031,105,106,1061,1071,1072,1073,1074,108,109,115";
//
//    /**
//     * 保存订单至Erp
//     * 迁移至PullNewOrderFromAeListener
//     */
//    public R<Object> saveListInErp(List<ErpSellerOrder> orderList) {
//        //循环该订单
//        Map<String, Object> map = new HashMap<>();
//        for (ErpSellerOrder order : orderList) {
//            //判断数据库中是否已存在该订单号
//            ErpSellerOrder erpSellerOrderSel = erpSellerOrderMapper.queryOrderByOrderId(order.getOrderId());
//            if (erpSellerOrderSel != null) {
//                //若已存在，则进入增量订单方法
//                order.setId(erpSellerOrderSel.getId());
//                if (erpSellerOrderSel.getErpInnerOrderStatus().equals("114")) {
//                    continue;
//                }
//                if (erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.Evaluation.getInfo())
//                        || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.Error.getInfo())
//                        || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.MySelf.getInfo())
//                        || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.Out.getInfo())
//                        || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.CompanyEva.getInfo())
//                        || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.Invalid.getInfo())) {
//                    //测评单和作废单不再更新状态
//                    continue;
//                }
//                map = disposeIncrementalOrders(order, erpSellerOrderSel);
//                if (map == null) {
////                    OrderLogType orderLogType = OrderLogType.CancelOrder;
////                    erpSellerOrderLogService.createOrderLog(order.getOrderId(), null, orderLogType, null, OrderProcessFlag.Problem.getInfo(), "701");
//                    continue;
//                }
//                order = (ErpSellerOrder) map.get("order");
//            } else {
//                //若不存在，则进入新订单方法
//                map = disposeNewOrders(order);
//                order = (ErpSellerOrder) map.get("order");
//                order.setCreateTime(new Date());
//            }
//
//            order.setUpdateTime(new Date());
//
//            //处理订单数据
//            insertOrUpdateOrder(order);
//            OrderLogType orderLogType = (OrderLogType) map.get("orderLogType");
//            String remark = (String) map.get("remark");
//            String orderProcessFlag = (String) map.get("orderProcessFlag");
//            String erpInnerOrderStatus = (String) map.get("erpInnerOrderStatus");
//            if (orderLogType != null) {
//                //当日志类型不为空时，再生成日志
//                //处理map，生成日志
//                //Long orderId, OrderLogType orderLogType, String remark, OrderProcessFlag orderProcessFlag
//                erpSellerOrderLogService.createOrderLog(order.getOrderId(), null, orderLogType, remark, orderProcessFlag, erpInnerOrderStatus);
//
//                //计算预估利润 TODO 后付费版 迁移暂时注释
//                orderInfoStatisticsService.saveOrderProfitInfo(order);
//
//                //判断是会否需要后付费 TODO 后付费版 迁移暂时注释
////                iErpSellerOrderService.freezeOrderAmount(order.getOrderId(), 0);
//
//                // 判断是否是网红产品 TODO 迁移暂时注释
////                iErpInternetCelebrityStatisticService.judgeProductAndSeller(order.getOrderId());
//
//            }
//
//
//        }
//
//
//        return R.ok("更新成功");
//    }

//    /**
//     * 处理新订单
//     * 迁移至PullNewOrderFromAeListener
//     */
//    public Map<String, Object> disposeNewOrders(ErpSellerOrder order) {
//        Map<String, Object> map = new HashMap<>();
//        //判断订单类型
//        String orderProcessFlag = null;
//        OrderLogType orderLogType = null;
//        String erpInnerOrderStatus = null;
//        String remark = "（订单已被获取到）";
//        switch (order.getOrderStatus()) {
//            case "PLACE_ORDER_SUCCESS":
//                //买家待支付
//                erpInnerOrderStatus = "100";
//                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
//                orderLogType = OrderLogType.CreateOrder;
//                break;
//            case "RISK_CONTROL":
//                //封控24小时
//                erpInnerOrderStatus = "102";
//                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
//                orderLogType = OrderLogType.RiskControlOrder;
//                break;
//            case "WAIT_SELLER_SEND_GOODS":
//                //待支付
//                erpInnerOrderStatus = "101";
//                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
//                orderLogType = OrderLogType.WaitSellerSendGoods;
////                findOrderReceiptInfo(order.getOrderId());
//
//                List<ErpSellerChildOrder> childOrders = erpSellerChildOrderMapper.selectList(
//                        new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, order.getOrderId())
//                );
//                if (childOrders.size() > 0) {
//                    List<String> skuCodeList = childOrders.stream()
//                            .map(ErpSellerChildOrder::getSkuCode)    // 抽出每个ErpSellerStoreProductGroup对象的id
//                            .collect(Collectors.toList());   // 创建新的集合
//                    for (String skuCode : skuCodeList) {
//                        remoteCollectProductService.setProToOrder(skuCode);
//                    }
//                }
//                break;
//            case "WAIT_BUYER_ACCEPT_GOODS":
//                //待收货
//                erpInnerOrderStatus = "107";
//                orderProcessFlag = OrderProcessFlag.Out.getInfo();
//                orderLogType = OrderLogType.OutOrderSendGoodsOK;
//                break;
//            case "FINISH":
//                //已结束
//                erpInnerOrderStatus = "114";
//                orderProcessFlag = OrderProcessFlag.Out.getInfo();
//                orderLogType = OrderLogType.OutOrderFinish;
//                break;
//            case "SELLER_PART_SEND_GOODS":
//                //部分支付
//                erpInnerOrderStatus = "701";
//                orderProcessFlag = OrderProcessFlag.Out.getInfo();
//                orderLogType = OrderLogType.OutOrderSendGoodsOK;
//                break;
//            default:
//                erpInnerOrderStatus = "701";
//                orderProcessFlag = OrderProcessFlag.Out.getInfo();
//                remark = problemRemark(order.getOrderStatus());
//                orderLogType = OrderLogType.OutOrderTurnProblem;
//                break;
//        }
//        order.setErpInnerOrderStatus(erpInnerOrderStatus);
//        order.setOrderProcessFlag(orderProcessFlag);
//        map.put("order", order);
//        map.put("orderProcessFlag", orderProcessFlag);
//        map.put("orderLogType", orderLogType);
//        map.put("remark", remark);
//        map.put("erpInnerOrderStatus", erpInnerOrderStatus);
//        return map;
//
//    }
//
    /**
     * 获取该订单的上一个流程代码
     *
     * @param orderId
     */
    private ErpSellerOrderLog findLastOrderLog(Long orderId) {
        List<ErpSellerOrderLog> logList = erpSellerOrderLogMapper.selectList(
                new LambdaQueryWrapper<ErpSellerOrderLog>()
                        .eq(ErpSellerOrderLog::getOrderId, orderId)
                        .orderByDesc(ErpSellerOrderLog::getCreateTime)
        );
        String previousStatus = null;
        for (ErpSellerOrderLog log : logList) {
            //查看日志的流程代码
            previousStatus = log.getPreviousStatus();
            if (previousStatus.equals("problem")) {
                continue;
            }
            return log;
        }
        return null;
    }
//
//    /**
//     * 问题单返回备注
//     *
//     * @param orderStatus
//     * @return
//     * 迁移至PullNewOrderFromAeListener
//     */
//    private String problemRemark(String orderStatus) {
//        String remark = null;
//        switch (orderStatus) {
//            case "IN_CANCEL":
//                remark = "买家申请取消";
//                break;
//            case "FUND_PROCESSING":
//                remark = "买卖家达成一致，资金处理中";
//                break;
//            case "IN_ISSUE":
//                remark = "含纠纷中的订单";
//                break;
//            case "IN_FROZEN":
//                remark = "冻结中的订单";
//                break;
//            case "WAIT_SELLER_EXAMINE_MONEY":
//                remark = "等待卖家确认金额";
//                break;
//            default:
//                remark = "其他问题(" + orderStatus + ")";
//                break;
//        }
//        return remark;
//    }
//
//    /**
//     * 更新/保存订单信息
//     *
//     * @param order
//     *
//     * 迁移至PullNewOrderFromAeListener
//     */
//    private void insertOrUpdateOrder(ErpSellerOrder order) {
//        if (order.getSellerChildOrderList() != null && order.getSellerChildOrderList().size() > 0) {
//            List<ErpCollectProductSku> erpCollectProductSku = new ArrayList<>();
//            ErpCollectAbsentSku erpCollectAbsentSku = new ErpCollectAbsentSku();
//            ErpCollectProductSku collectProductSku = null;
//            //向优先采集表中插入信息
//            for (ErpSellerChildOrder erpSellerChildOrder : order.getSellerChildOrderList()) {
//                //判断该订单的商品的skucode在数据库中是否存在
//                collectProductSku = new ErpCollectProductSku();
//                collectProductSku.setSkuCode(erpSellerChildOrder.getSkuCode());
//                collectProductSku.setDelFlag("0");
//                erpCollectProductSku = remoteCollectProductSkuService.getCollectProductSkuList(collectProductSku);
//                if (erpCollectProductSku.size() > 0) {
//                    //查询该商品是否已属于该表
//                    erpCollectAbsentSku = remoteCollectAbsentSkuService.getBySkuCode(erpSellerChildOrder.getSkuCode());
//                    if (erpCollectAbsentSku == null) {
//                        erpCollectAbsentSku = new ErpCollectAbsentSku();
//                        String url = "https://www.aliexpress.us/item/";
//                        //向晓翔表里插入数据
//                        erpCollectAbsentSku.setOrderId(erpSellerChildOrder.getOrderId().toString());
//                        erpCollectAbsentSku.setChildOrderId(erpSellerChildOrder.getChildOrderId());
//                        erpCollectAbsentSku.setSkuCode(erpSellerChildOrder.getSkuCode());
//                        erpCollectAbsentSku.setCollectLink(url + erpSellerChildOrder.getProductId() + ".html");
//                        erpCollectAbsentSku.setStatus("0");
//                        remoteCollectAbsentSkuService.addSku(erpCollectAbsentSku);
//                    }
//                }
//                erpSellerChildOrderMapper.insertOrUpdate(BeanUtil.copyProperties(erpSellerChildOrder, ErpSellerChildOrder.class));
//            }
//        }
//
//        if (order.getSellerOrderProductList().size() > 0) {
//            for (ErpSellerOrderProduct orderProduct : order.getSellerOrderProductList()) {
//                ErpSellerOrderProduct orderProductSel = new ErpSellerOrderProduct();
//                if (ObjectUtils.isNotNull(orderProduct.getSkuCode())) {
//                    orderProductSel = erpSellerOrderProductMapper.selectOne(
//                            new LambdaQueryWrapper<ErpSellerOrderProduct>()
//                                    .eq(ErpSellerOrderProduct::getSkuCode, orderProduct.getSkuCode())
//                                    .eq(ErpSellerOrderProduct::getChildId, orderProduct.getChildId())
//                                    .eq(ErpSellerOrderProduct::getOrderId, orderProduct.getOrderId())
//                    );
//                } else {
//                    orderProductSel = erpSellerOrderProductMapper.selectOne(
//                            new LambdaQueryWrapper<ErpSellerOrderProduct>()
//                                    .eq(ErpSellerOrderProduct::getChildId, orderProduct.getChildId())
//                                    .eq(ErpSellerOrderProduct::getOrderId, orderProduct.getOrderId())
//                                    .last("limit 1")
//                    );
//                }
//
//                if (orderProductSel != null) {
//                    orderProduct.setId(orderProductSel.getId());
//                }
//                orderProduct.setCreateTime(new Date());
//                orderProduct.setUpdateTime(new Date());
//                erpSellerOrderProductMapper.insertOrUpdate(orderProduct);
//            }
//        }
//
//        //修改订单
//        erpSellerOrderMapper.insertOrUpdate(order);
//
//    }
//
//
//    @Override
//    public void updateOrderStatusNew(String orderStatus) {
//        List<ErpSellerOrder> orderList = erpSellerOrderMapper.selectList(
//                new LambdaQueryWrapper<ErpSellerOrder>()
//                        .eq(ErpSellerOrder::getErpInnerOrderStatus, orderStatus)
//                        .inSql(ErpSellerOrder::getSellerLoginId, "select store_user_name from erp_seller_store_empower where is_empower = 1 and del_flag = 0")
//                        .notIn(ErpSellerOrder::getOrderProcessFlag, "Evaluation", "CompanyEva", "MySelf", "Out", "Invalid")
//        );
//        for (ErpSellerOrder order : orderList) {
//            updateOrderStatus(order);
//        }
//    }
//
//    @Override
//    public void updateOrderStatusByOrderId(String orderId) {
//        List<ErpSellerOrder> orderList = erpSellerOrderMapper.selectList(
//                new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId)
//        );
//        for (ErpSellerOrder order : orderList) {
//            updateOrderStatus(order);
//        }
//    }
//
//    @Override
//    public void processingOrderLog(String orderProcessFlag, String orderStatus) {
//        List<ErpSellerOrder> orderList = erpSellerOrderMapper.selectList(
//                new LambdaQueryWrapper<ErpSellerOrder>()
//                        .eq(ErpSellerOrder::getOrderProcessFlag, orderProcessFlag)
//                        .eq(ErpSellerOrder::getOrderStatus, orderStatus)
//                        .inSql(ErpSellerOrder::getSellerLoginId, "select store_user_name from erp_seller_store_empower where is_empower = 1")
//
//        );
//
//        //转为问题件
//        OrderLogType newOrderLogType = null;
//        OrderProcessFlag newOrderProcessFlag = null;
//        String newAeOrderStatus = null;
//        String newErpOrderStatus = null;
//
//        if (orderStatus.equals("FINISH")) {
//            newOrderLogType = OrderLogType.OrderTurnProblemForFinish;
//            newOrderProcessFlag = OrderProcessFlag.Problem;
//            newAeOrderStatus = orderStatus;
//            newErpOrderStatus = "114";
//        } else if (orderStatus.equals("WAIT_BUYER_ACCEPT_GOODS")) {
//            newOrderLogType = OrderLogType.OrderTurnProblemForSendGoodsOK;
//            newOrderProcessFlag = OrderProcessFlag.Problem;
//            newAeOrderStatus = orderStatus;
//            newErpOrderStatus = "107";
//        }
//
//        for (ErpSellerOrder order : orderList) {
//            erpSellerOrderLogService.createOrderLog(order.getOrderId(), null, newOrderLogType, null, newOrderProcessFlag.getInfo(), newErpOrderStatus);
//            iErpSellerOrderService.updateInnerStatusAndProcess(order.getOrderId(), newAeOrderStatus, newOrderProcessFlag.getInfo(), newErpOrderStatus);
//        }
//    }

    /**
     * 处理增量订单
     */
//    @Override
    public Map<String, Object> disposeIncrementalOrders(ErpSellerOrder order, ErpSellerOrder erpSellerOrderSel) {
        //测评单和作废单不再更新状态
        if (erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.Evaluation.getInfo())
                || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.Error.getInfo())
                || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.MySelf.getInfo())
                || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.Out.getInfo())
                || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.CompanyEva.getInfo())
                || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.Invalid.getInfo())) {
            return null;
        }

        Map<String, Object> map = new HashMap<>();
        //判断订单类型
        String orderProcessFlag = null;
        OrderLogType orderLogType = null;
        String remark = null;

        //erp内部状态
        String erpOrderStatus = erpSellerOrderSel.getErpInnerOrderStatus();
        //erp当前速卖通状态
        String nowOrderStatus = erpSellerOrderSel.getOrderStatus();
        //速卖通当前速卖通状态
        String newOrderStatus = order.getOrderStatus();

        ErpSellerOrderLog lastOrderLog = new ErpSellerOrderLog();

        //订单状态策略
        Map<String, Object> orderStatusTacticsMap = AeSaveOrderServiceImpl.orderStatusTacticsMap;
//        System.out.println(orderStatusTacticsMap);
        String prbNowStatus = nowOrderStatus;
        String prbNewStatus = newOrderStatus;
        if (!statusStr.contains(nowOrderStatus)) {
            prbNowStatus = "PROBLEM";
        }
        if (!statusStr.contains(newOrderStatus)) {
            prbNewStatus = "PROBLEM";
        }
        //订单组合
        String orderTactics = prbNowStatus + "-" + prbNewStatus;
        System.out.println(orderTactics);
        //获取对应策略
        String tactics = (String) orderStatusTacticsMap.get(orderTactics);
        System.out.println(order.getOrderId() + ":" + orderTactics);
        if (tactics == null) {
            return null;
        }
        switch (tactics) {
            case "100":
                //正常流程，流程代码不变
                break;
            case "101":
                //流程代码不变，状态变为101 未付款-待发货 风控-待发货
                erpOrderStatus = "101";
                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                orderLogType = OrderLogType.WaitSellerSendGoods;
                findOrderReceiptInfo(order.getOrderId());

                List<ErpSellerChildOrder> childOrders = erpSellerChildOrderMapper.selectList(
                        new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, order.getOrderId())
                );
                if (childOrders.size() > 0) {
                    List<String> skuCodeList = childOrders.stream()
                            .map(ErpSellerChildOrder::getSkuCode)    // 抽出每个ErpSellerStoreProductGroup对象的id
                            .collect(Collectors.toList());   // 创建新的集合
                    for (String skuCode : skuCodeList) {
                        remoteCollectProductService.setProToOrder(skuCode);
                    }
                }
                break;
            case "102":
                //流程代码不变，状态变为102 未付款-封控
                erpOrderStatus = "102";
                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                orderLogType = OrderLogType.RiskControlOrder;
                break;
            case "103":
                //流程代码变为problem,状态变为107 未付款，封控，待发货-已发货
                erpOrderStatus = "107";
                orderProcessFlag = OrderProcessFlag.Problem.getInfo();
                orderLogType = OrderLogType.OrderTurnProblemForSendGoodsOK;
                break;
            case "104":
                if (inProcessOrderStatus.contains(erpSellerOrderSel.getErpInnerOrderStatus())) {
                    //订单在采购流程中结束
                    //流程代码变为异常,状态不变
                    erpOrderStatus = erpSellerOrderSel.getErpInnerOrderStatus();
                    orderProcessFlag = OrderProcessFlag.Error.getInfo();
                    orderLogType = OrderLogType.inTheProcessOrderErrorFinish;
                    remark = "disposeIncrementalOrders";
                } else {
                    erpOrderStatus = "114";
                    orderProcessFlag = erpSellerOrderSel.getOrderProcessFlag();
                    orderLogType = OrderLogType.OrderTurnFinish;
                }
                break;
            case "105":
                //流程代码变为problem,状态变为701
                erpOrderStatus = "701";
                orderProcessFlag = OrderProcessFlag.Problem.getInfo();
                orderLogType = OrderLogType.OrderTurnProblem;
//                remark = problemRemark(newOrderStatus);
                break;
            case "106":
                //PROBLEM 问题件转待付款 PLACE_ORDER_SUCCESS
                erpOrderStatus = "100";
                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                orderLogType = OrderLogType.ProblemOrderTurnPlaceOrder;
                break;
            case "107":
                //问题件转风控
                erpOrderStatus = "102";
                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                orderLogType = OrderLogType.ProblemOrderTurnRiskControlOrder;
                break;
            case "108":
                //问题件转待发货 流程代码往上，有没有菜鸟、线下、测评、自发货的订单，如果有则流程代码返回上一层级701-对应状态。如果没有，则流程代码不变，701-101
                lastOrderLog = findLastOrderLog(order.getOrderId());
                if (lastOrderLog != null) {
                    erpOrderStatus = lastOrderLog.getPreviousStatus();
                    orderProcessFlag = lastOrderLog.getPreviousOrderProcess();
                    orderLogType = OrderLogType.ProblemOrderTurnLastProcessOrder;
                } else {
                    erpOrderStatus = "101";
                    orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                    orderLogType = OrderLogType.ProblemOrderTurnSendGoodsOrder;
                }
                break;
            case "109":
                //问题件转已发货 流程代码往上找，有没有菜鸟、线下、测评、自发、作废、截单的订单，如果有则流程代码返回上一层级701-107。如果没有，则流程代码不变，701-107
                lastOrderLog = findLastOrderLog(order.getOrderId());
                orderLogType = OrderLogType.ProblemOrderTurnSendGoodsOKOrder;
                if (lastOrderLog != null) {
                    orderProcessFlag = lastOrderLog.getPreviousOrderProcess();
                    orderLogType = OrderLogType.ProblemOrderTurnLastProcessOrder;
                }
                erpOrderStatus = "107";
                break;
            case "110":
                //问题件转已完成
                orderProcessFlag = OrderProcessFlag.Problem.getInfo();
                orderLogType = OrderLogType.ProblemOrderTurnFinishOrder;
                erpOrderStatus = "114";
                break;
            case "111":
                //问题件变问题件，流程代码仍为problem，但remark可能要更新
                lastOrderLog = findLastOrderLog(order.getOrderId());
                //上个问题件的异常原因
//                remark = problemRemark(lastOrderLog.getRemark());
                //本次异常原因
//                String nowRemark = problemRemark(newOrderStatus);
                //进行比对
//                if (!nowRemark.equals(remark)) {
//                    //获取最开始时的问题件转化信息
//                    orderProcessFlag = OrderProcessFlag.Problem.getInfo();
//                    erpOrderStatus = "701";
//                    orderLogType = OrderLogType.NewProblem;
//                }
                break;
            case "112":
                //已发货变为已完成
//                if (inProcessOrderStatus.contains(erpSellerOrderSel.getErpInnerOrderStatus())) {
//                    //订单在采购流程中结束
//                    //流程代码变为异常,状态不变
//                    erpOrderStatus = erpSellerOrderSel.getErpInnerOrderStatus();
//                    orderProcessFlag = OrderProcessFlag.Error.getInfo();
//                    orderLogType = OrderLogType.inTheProcessOrderErrorFinish;
//                } else {
                //流程代码变为problem,状态变为114
                erpOrderStatus = "114";
                orderProcessFlag = erpSellerOrderSel.getOrderProcessFlag();
                orderLogType = OrderLogType.OrderTurnFinish;
//                }
                break;
        }

        //若订单是测评单或作废单，则订单后续流程应不变

        order.setOrderProcessFlag(orderProcessFlag);
        order.setErpInnerOrderStatus(erpOrderStatus);

        map.put("orderLogType", orderLogType);
        map.put("remark", remark);
        map.put("orderProcessFlag", orderProcessFlag);
        map.put("erpInnerOrderStatus", erpOrderStatus);

        map.put("order", order);
        map.put("erpOrderStatus", erpOrderStatus);
        return map;
    }
//
//
//    public void updateOrderStatus(ErpSellerOrder order) {
//        //测评单和作废单不再更新状态
//        if (order.getOrderProcessFlag().equals(OrderProcessFlag.Evaluation.getInfo())
//                || order.getOrderProcessFlag().equals(OrderProcessFlag.CompanyEva.getInfo())
//                || order.getOrderProcessFlag().equals(OrderProcessFlag.MySelf.getInfo())
//                || order.getOrderProcessFlag().equals(OrderProcessFlag.Out.getInfo())
//                || order.getOrderProcessFlag().equals(OrderProcessFlag.Invalid.getInfo())) {
//            return;
//        }
//
//        Map<String, Object> map = new HashMap<>();
//        ErpSellerStoreEmpower store = new ErpSellerStoreEmpower();
//        store = erpSellerStoreEmpowerMapper.selectStoreByStoreUserName(order.getSellerLoginId());
//        if (ObjectUtils.isEmpty(store)) {
//            return;
//        }
//        Map<String, Object> sendMap = new HashMap<>();
//        sendMap.put("orderId", order.getOrderId());
//        sendMap.put("storeId", store.getId());
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpOrder/findOrderBaseInfo", sendMap, String.class);
//        String body = (String) forEntity.getBody();
//        if (!body.contains("aliexpress_trade_redefining_findorderbaseinfo_response")) {
//            return;
//        }
//
//        //判断订单类型
//        String orderProcessFlag = null;
//        OrderLogType orderLogType = null;
//        String remark = null;
//        //erp内部状态
//        String erpOrderStatus = null;
//        //erp当前速卖通状态
//        String nowOrderStatus = order.getOrderStatus();
//        //速卖通当前速卖通状态
//        String newOrderStatus = null;
//
//        String data = JSONObject.parseObject(body).getString("data");
//        if (body.contains("{}")) {
////            if (nowOrderStatus.equals("FINISH")) {
//            return;
////            }
////            if (order.getErpInnerOrderStatus().equals("107")) {
////                erpOrderStatus = "107";
////                orderProcessFlag = order.getOrderProcessFlag();
////                orderLogType = OrderLogType.SendGoodsOkOrderError;
////                newOrderStatus = "WAIT_BUYER_ACCEPT_GOODS";
////            } else {
////                erpOrderStatus = "114";
////                orderProcessFlag = OrderProcessFlag.Out.getInfo();
////                orderLogType = OrderLogType.BuyerPaymentTimeout;
////                newOrderStatus = "FINISH";
////            }
////            erpOrderStatus = order.getErpInnerOrderStatus();
////            orderProcessFlag = OrderProcessFlag.Error.getInfo();
////            orderLogType = OrderLogType.OrderError;
////            newOrderStatus = order.getOrderStatus();
//        } else {
//            //Ae最新状态
//            newOrderStatus = JSONObject.parseObject(data)
//                    .getJSONObject("aliexpress_trade_redefining_findorderbaseinfo_response")
//                    .getJSONObject("result")
//                    .getString("order_status");
//
//            ErpSellerOrderLog lastOrderLog = new ErpSellerOrderLog();
//
//
//            //订单状态策略
//            Map<String, Object> orderStatusTacticsMap = AeSaveOrderServiceImpl.orderStatusTacticsMap;
////        System.out.println(orderStatusTacticsMap);
//            String prbNowStatus = nowOrderStatus;
//            String prbNewStatus = newOrderStatus;
//            if (!statusStr.contains(nowOrderStatus)) {
//                prbNowStatus = "PROBLEM";
//            }
//            if (!statusStr.contains(newOrderStatus)) {
//                prbNewStatus = "PROBLEM";
//            }
//            //订单组合
//            String orderTactics = prbNowStatus + "-" + prbNewStatus;
////        System.out.println(orderTactics);
//            //获取对应策略
//            String tactics = (String) orderStatusTacticsMap.get(orderTactics);
//            System.out.println(order.getOrderId() + ":" + orderTactics);
//            if (tactics == null) {
//                return;
//            }
//            switch (tactics) {
//                case "100":
//                    //正常流程，流程代码不变
//                    break;
//                case "101":
//                    //流程代码不变，状态变为101 未付款-待发货 风控-待发货
//                    erpOrderStatus = "101";
//                    orderProcessFlag = OrderProcessFlag.Begin.getInfo();
//                    orderLogType = OrderLogType.WaitSellerSendGoods;
//                    findOrderReceiptInfo(order.getOrderId());
//
//                    List<ErpSellerChildOrder> childOrders = erpSellerChildOrderMapper.selectList(
//                            new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, order.getOrderId())
//                    );
//                    if (childOrders.size() > 0) {
//                        List<String> skuCodeList = childOrders.stream()
//                                .map(ErpSellerChildOrder::getSkuCode)    // 抽出每个ErpSellerStoreProductGroup对象的id
//                                .collect(Collectors.toList());   // 创建新的集合
//                        for (String skuCode : skuCodeList) {
//                            iErpCollectProductService.setProToOrder(skuCode);
//                        }
//                    }
//                    break;
//                case "102":
//                    //流程代码不变，状态变为102 未付款-封控
//                    erpOrderStatus = "102";
//                    orderProcessFlag = OrderProcessFlag.Begin.getInfo();
//                    orderLogType = OrderLogType.RiskControlOrder;
//                    break;
//                case "103":
//                    //流程代码变为problem,状态变为107 未付款，封控，待发货-已发货
//                    erpOrderStatus = "107";
//                    orderProcessFlag = OrderProcessFlag.Problem.getInfo();
//                    orderLogType = OrderLogType.OrderTurnProblemForSendGoodsOK;
//                    break;
//                case "104":
//                    //待发货变为已完成
//                    if (inProcessOrderStatus.contains(order.getErpInnerOrderStatus())) {
//                        //订单在采购流程中结束
//                        //流程代码变为异常,状态不变
//                        erpOrderStatus = order.getErpInnerOrderStatus();
//                        orderProcessFlag = OrderProcessFlag.Error.getInfo();
//                        orderLogType = OrderLogType.inTheProcessOrderErrorFinish;
//                        remark = "updateOrderStatus";
//                    } else {
//                        //流程代码变为problem,状态变为114
//                        erpOrderStatus = "114";
//                        orderProcessFlag = order.getOrderProcessFlag();
//                        orderLogType = OrderLogType.OrderTurnFinish;
//                    }
//                    break;
//                case "105":
//                    //流程代码变为problem,状态变为701
//                    erpOrderStatus = "701";
//                    orderProcessFlag = OrderProcessFlag.Problem.getInfo();
//                    orderLogType = OrderLogType.OrderTurnProblem;
//                    remark = problemRemark(newOrderStatus);
//                    break;
//                case "106":
//                    //PROBLEM 问题件转待付款 PLACE_ORDER_SUCCESS
//                    erpOrderStatus = "100";
//                    orderProcessFlag = OrderProcessFlag.Begin.getInfo();
//                    orderLogType = OrderLogType.ProblemOrderTurnPlaceOrder;
//                    break;
//                case "107":
//                    //问题件转风控
//                    erpOrderStatus = "102";
//                    orderProcessFlag = OrderProcessFlag.Begin.getInfo();
//                    orderLogType = OrderLogType.ProblemOrderTurnRiskControlOrder;
//                    break;
//                case "108":
//                    //问题件转待发货 流程代码往上，有没有菜鸟、线下、测评、自发货的订单，如果有则流程代码返回上一层级701-对应状态。如果没有，则流程代码不变，701-101
//                    lastOrderLog = findLastOrderLog(order.getOrderId());
//                    if (lastOrderLog != null) {
//                        erpOrderStatus = lastOrderLog.getPreviousStatus();
//                        orderProcessFlag = lastOrderLog.getPreviousOrderProcess();
//                        orderLogType = OrderLogType.ProblemOrderTurnLastProcessOrder;
//                    } else {
//                        erpOrderStatus = "101";
//                        orderProcessFlag = OrderProcessFlag.Begin.getInfo();
//                        orderLogType = OrderLogType.ProblemOrderTurnSendGoodsOrder;
//                    }
//                    break;
//                case "109":
//                    //问题件转已发货 流程代码往上找，有没有菜鸟、线下、测评、自发、作废、截单的订单，如果有则流程代码返回上一层级701-107。如果没有，则流程代码不变，701-107
//                    lastOrderLog = findLastOrderLog(order.getOrderId());
//                    orderLogType = OrderLogType.ProblemOrderTurnSendGoodsOKOrder;
//                    if (lastOrderLog != null) {
//                        orderProcessFlag = lastOrderLog.getPreviousOrderProcess();
//                        orderLogType = OrderLogType.ProblemOrderTurnLastProcessOrder;
//                    }
//                    erpOrderStatus = "107";
//                    break;
//                case "110":
//                    //问题件转已完成
//                    orderProcessFlag = OrderProcessFlag.Problem.getInfo();
//                    orderLogType = OrderLogType.ProblemOrderTurnFinishOrder;
//                    erpOrderStatus = "114";
//                    break;
//                case "111":
//                    //问题件变问题件，流程代码仍为problem，但remark可能要更新
//                    lastOrderLog = findLastOrderLog(order.getOrderId());
//                    //上个问题件的异常原因
//                    remark = problemRemark(lastOrderLog.getRemark());
//                    //本次异常原因
//                    String nowRemark = problemRemark(newOrderStatus);
//                    //进行比对
//                    if (!nowRemark.equals(remark)) {
//                        //获取最开始时的问题件转化信息
//                        orderProcessFlag = OrderProcessFlag.Problem.getInfo();
//                        erpOrderStatus = "701";
//                        orderLogType = OrderLogType.NewProblem;
//                    }
//                    break;
//                case "112":
//                    //已发货变为已完成
////                    if (inProcessOrderStatus.contains(order.getErpInnerOrderStatus())) {
////                        //订单在采购流程中结束
////                        //流程代码变为异常,状态不变
////                        erpOrderStatus = order.getErpInnerOrderStatus();
////                        orderProcessFlag = OrderProcessFlag.Error.getInfo();
////                        orderLogType = OrderLogType.inTheProcessOrderErrorFinish;
////                    } else {
//                    //流程代码变为problem,状态变为114
//                    erpOrderStatus = "114";
//                    orderProcessFlag = order.getOrderProcessFlag();
//                    orderLogType = OrderLogType.OrderTurnFinish;
////                    }
//                    break;
//            }
////            order.setErpInnerOrderStatus(erpOrderStatus);
////            order.setOrderProcessFlag(orderProcessFlag);
////            map.put("order", order);
////            map.put("orderLogType", orderLogType);
////            map.put("orderProcessFlag", orderProcessFlag);
////            map.put("erpInnerOrderStatus", erpOrderStatus);
////            map.put("remark", remark);
//        }
//        if (erpOrderStatus != null && erpOrderStatus.equals("114")) {
//            ResponseEntity<String> orderEntity = restTemplate
//                    .postForEntity(aeConfig.getEndpoint() + "/AEOrder/storeOrder/findOrderById", sendMap, String.class);
//            String orderInfo = (String) orderEntity.getBody();
//            String code = JSONObject.parseObject(orderInfo).getString("code");
//            if (code.equals("200")) {
//                //放入原因
//                String msg = JSONObject
//                        .parseObject(orderInfo)
//                        .getJSONObject("msg").toString();
//                if (msg.contains("order_end_reason")) {
//                    String orderEndReason = JSONObject
//                            .parseObject(orderInfo)
//                            .getJSONObject("msg")
//                            .getJSONObject("aliexpress_trade_new_redefining_findorderbyid_response")
//                            .getJSONObject("target")
//                            .getString("order_end_reason");
//                    if (orderEndReason != null) {
//                        remark = orderEndReason;
//                    }
//                } else {
//                    return;
//                }
//            }
//        }
//
//        //创建日志
//        if (orderLogType != null) {
//            erpSellerOrderLogService.createOrderLog(order.getOrderId(), null, orderLogType, remark, orderProcessFlag, erpOrderStatus);
//            iErpSellerOrderService.updateInnerStatusAndProcess(order.getOrderId(), newOrderStatus, orderProcessFlag, erpOrderStatus);
//        }
//    }
//
//    /**
//     * 回退异常单
//     *
//     * @return
//     */
//    @Override
//    public R<Object> fallbackErrorOrder(Long orderId, String orderProcessFlag) {
//        List<ErpSellerOrderLog> logList = new ArrayList<>();
//        if (ObjectUtils.isNotEmpty(orderId)) {
//            logList = erpSellerOrderLogMapper.selectList(
//                    new LambdaQueryWrapper<ErpSellerOrderLog>()
//                            .eq(ErpSellerOrderLog::getCurrentOrderProcess, OrderProcessFlag.Error.getInfo())
//                            .eq(ErpSellerOrderLog::getPreviousOrderProcess, orderProcessFlag)
//                            .eq(ErpSellerOrderLog::getOrderId, orderId)
//            );
//        } else {
//            logList = erpSellerOrderLogMapper.selectList(
//                    new LambdaQueryWrapper<ErpSellerOrderLog>()
//                            .eq(ErpSellerOrderLog::getCurrentOrderProcess, OrderProcessFlag.Error.getInfo())
//                            .eq(ErpSellerOrderLog::getPreviousOrderProcess, orderProcessFlag)
//            );
//        }
//
//        logList.forEach(log -> {
//            ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(log.getOrderId());
//            order.setOrderProcessFlag(orderProcessFlag);
//            erpSellerOrderMapper.updateById(order);
//            erpSellerOrderLogMapper.deleteById(log);
//        });
//
//        return R.ok("已重置");
//    }
//
    public R<Object> findOrderReceiptInfo(Long orderId) {
        List<ErpSellerOrder> orderList = new ArrayList<>();
        if (orderId != null) {
            ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(orderId);
            if (ObjectUtils.isEmpty(order)) {
                order = new ErpSellerOrder();
            }
            order.setOrderId(orderId);
            orderList.add(order);
        } else {
            orderList = erpSellerOrderMapper.selectAddressErrorList();
        }
        for (ErpSellerOrder orderFor : orderList) {
            System.out.println(orderFor);
            Map<String, Object> sendMap = new HashMap<>();
//            sendMap.put("orderId", orderFor.getOrderId());
            // 获取店铺授权信息
            R<Object> storeEmpowerObject = remoteSellerStoreService.getSellerStoreEmpowerByCnCode(orderFor.getSellerLoginId());
            if(storeEmpowerObject.getCode() != 200){
                R.fail("获取店铺授权信息错误，日志添加失败");
            }
            String storeEmpowerString = JSONObject.toJSONString(storeEmpowerObject.getData());
            ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(storeEmpowerString, ErpSellerStoreEmpower.class);

//            sendMap.put("storeId", storeEmpower.getId());
            R<Object> orderObject = remoteAeOrderService.findOrderReceiptInfo(storeEmpower.getId()+"", orderFor.getOrderId()+"");

            ErpSellerOrderExtend orderExtend = erpSellerOrderExtendMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, orderFor.getOrderId())
            );
            if (orderExtend == null) {
                orderExtend = new ErpSellerOrderExtend();
                orderExtend.setOrderId(orderFor.getOrderId());
            }
            if (orderObject.getCode() == 200) {
                orderExtend.setType("1");
            } else {
                orderExtend.setType("0");
            }
            erpSellerOrderExtendMapper.insertOrUpdate(orderExtend);
        }
        return R.ok("更新成功");
    }
//
//
//    /**
//     * @Description: 4.0.0以后合并至pullOrdersFromAliExpress方法统一入口
//     * @Version: 4.0.0
//    **/
//    @Override
//    public R<Object> pullOrdersFromAliExpress(Long storeId, String createDateStart, String createDateEnd) {
//        PullOrderFromAeParam pullOrderFromAeParam = new PullOrderFromAeParam();
//        pullOrderFromAeParam.setStoreId(storeId.toString());
//        if (createDateStart == null) {
//            //获取五天前的时间
//            //当前时间
//            LocalDateTime now = LocalDateTime.now();
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            // 格式化当前时间
//            String endFormatted = now.format(formatter);
//            LocalDateTime parse = LocalDateTime.parse(endFormatted, formatter);
//            LocalDateTime zeroHour = parse.plusDays(-3).withHour(0).withMinute(0).withSecond(0).withNano(0);
//            String createFormatted = zeroHour.format(formatter);
//            createDateStart = createFormatted;
//            createDateEnd = endFormatted;
//        }
//        pullOrderFromAeParam.setCreateDateStart(TimeZoneTransition.transition(createDateStart));
//        pullOrderFromAeParam.setCreateDateEnd(TimeZoneTransition.transition(createDateEnd));
//        pullOrderFromAeParam.setCurrentpage("1");
//        pullOrderFromAeParam.setPageSize(100);
//
//        System.out.println(pullOrderFromAeParam.toString());
//
//        R<Object> returnResponse = remoteAeOrderService.pullOrdersFromAliExpress(pullOrderFromAeParam);
//
//        if (returnResponse.getCode() != 200) {
//            return null;
//        }
//
//        String data = JSONObject.toJSONString(returnResponse.getData());
//        //将获取的result进行解码
//        System.out.println(data);
//        List<ErpSellerOrder> orderList = JSONArray.parseArray(data, ErpSellerOrder.class);
//        //for循环存入数据库
//        return saveListInErp(orderList);
//    }
}

